// 自调用函数，开启一个新的局部作用域，避免命名冲突
(function(){
  var that;
  function Game(map){
    this.food = new Food();
    this.snack = new Snack();
    this.map = map;
    that = this;
  }
  Game.prototype.start = function(){
    // 1 把蛇和食物对象，渲染到地图上
    this.food.render(this.map);
    this.snack.render(this.map);
    
    // 2 开始游戏的逻辑
    // 2.1 让蛇移动起来  
    runSnack();
    
    // 2.2 通过键盘控制蛇移动的方向
    bindKey();
    // 2.3 当蛇遇到食物 做相应的处理
  }

  // 定义一个私有函数
  function runSnack (){
    var timeId = setInterval(function(){
      that.snack.move(that.food,that.map);
      that.snack.render(that.map);
      // 2.2 当蛇遇到边界的时候游戏结束
      var maxX = that.map.offsetWidth / that.snack.width;
      var maxY = that.map.offsetHeight / that.snack.height;
      var headX = that.snack.body[0].x;
      var headY = that.snack.body[0].y;
      if(headX < 0 || headX >= maxX){
        alert("Game Over");
        clearInterval(timeId);
        return;
      }
      if(headY < 0 || headY > maxY){
        alert("Game Over");
        clearInterval(timeId);
        return;
      }
    },150)
  }

  // 通过键盘控制蛇移动的方向
  function bindKey (){
    document.addEventListener('keydown',function(e){
      // 37 --- left
      // 38----top
      // 39 --- right
      // 40--- bottom
      switch(e.keyCode){
        case 37:
        that.snack.direction = "left";
        break;
        case 38:
        that.snack.direction = "top";
        break;
        case 39:
        that.snack.direction = "right";
        break;
        case 40:
        that.snack.direction = "bottom";
        break;
      }
    },false)
  }

  // 暴露构造函数到外部
  window.Game = Game;
})()

